package com.teamclub.app.sservices.systemmanager

import io.ebean.{Ebean, ExpressionList}
import com.fasterxml.jackson.databind.JsonNode
import com.teamclub.app.sforms.AppSubjectUserForm
import com.teamclub.domain.system.AppSubjectUser
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.{F, MD5}
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

/**
  * Created by ilkkzm on 17-7-27.
  */

@Service
class AppSubjectUserService {

  def expr(where: ExpressionList[AppSubjectUser], form: AppSubjectUserForm) {
    if(form.id != null) {
      where.eq("id", form.id)
    }
    if(StringUtils.isNotBlank(form.userName)){
      where.like("userName", '%' + form.userName + '%')
    }
    if(StringUtils.isNotBlank(form.realName)) {
      where.like("realName", '%' + form.realName + '%')
    }
    if(StringUtils.isNotBlank(form.organNo)) {
      where.eq("organNo", form.organNo)
    }
    if(form.archId != null) {
      where.eq("archId", form.archId)
    }
  }

  def list(form: AppSubjectUserForm): F.Either[JsonNode, ErrorCode] = {
    val where = Ebean.find(classOf[AppSubjectUser]).where()
    expr(where, form)
    F.Either.Left(Pager.genePagerJson(where.query(), form))
  }

  def add(form: AppSubjectUserForm): F.Either[AppSubjectUser, ErrorCode] = {
    var single = new AppSubjectUser
    if(form.id != null) {
      single = Ebean.find(classOf[AppSubjectUser], form.id)
      if(single == null) {
        return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
      }
      if(single.getOrganNo == single.getUserName) {
        if(form.getOrganNo != form.getUserName) {
          return F.Either.Right(ErrorCode.ENTITY_NOT_PERMIT_MODIFY)
        }
      }
    }
    BeanUtils.copyProperties(form, single)
    if(form.id != null) {
      single.update()
    } else {
      single.save()
    }
    F.Either.Left(single)
  }

  def del(form: AppSubjectUserForm): F.Either[AppSubjectUser, ErrorCode] = {
    val single = Ebean.find(classOf[AppSubjectUser], form.id)
    if(single == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      if(single.getOrganNo == single.getUserName) {
        return F.Either.Right(ErrorCode.ENTITY_NOT_PERMIT_MODIFY)
      }
      single.delete()
      F.Either.Left(single)
    }
  }

  def judgeIsRegister(form: AppSubjectUserForm): F.Either[Boolean, ErrorCode] = {
    val count = Ebean.find(classOf[AppSubjectUser]).where().eq("telephone", form.telephone).eq("appDomain", form.appDomain).eq("isAdmin", 1).findCount()
    if (count > 0) {
      F.Either.Right(ErrorCode.ref("该手机号码已经注册"))
    } else {
      F.Either.Left(true)
    }
  }

}
